﻿var access_token;
var prev_access_token, cur_access_token;
window.FB = FBWinJS;
var share = false;
var myFriends = null;
var playCheck = false;

/*Enter your app-id from facebook for your app here.*/
FB.options({
    appId: 'xxxxxxxxxxxxxxxxxxx'
});

var myAdControl;

(function () {
    "use strict";
    
    var page = WinJS.UI.Pages.define("/html/adShare.html", {
        ready: function (element, options) {
            
            /*The code in ready function goes into the block of your app.load() function */
            var adDiv = document.getElementById("myAd");
            myAdControl = new MicrosoftNSJS.Advertising.AdControl(adDiv,
                            {
                                applicationId: "d25517cb-12d4-4699-8bdc-52040c712cab",
                                adUnitId: "10043105"
                            });
            myAdControl.onErrorOccurred = window.errorLogger;
            document.getElementById("share2PurchaseButton").addEventListener("click", shareProduct2, false);
            document.getElementById("adStatus").addEventListener("click", getStatus, false);
            document.getElementById("resumeAd").addEventListener("click", resumeAd, false);

            
            function resumeAd() {
                if (myAdControl.isSuspended) {
                    
                    var adDiv = document.getElementById("myAd");

                    myAdControl = new MicrosoftNSJS.Advertising.AdControl(adDiv,
                                    {
                                        applicationId: "d25517cb-12d4-4699-8bdc-52040c712cab",
                                        adUnitId: "10043105"
                                    });


                    myAdControl.resume();
                    WinJS.log && WinJS.log("The ad is restarted", "sample", "status");


                }
                else {
                    //document.getElementById("state").innerText = "The Ad is running normally";
                    WinJS.log && WinJS.log("The ad is already running normally", "sample", "status");
                }
            }

            WinJS.Utilities.markSupportedForProcessing(
            window.errorLogger = function (sender, evt) {
                adEvents.innerHTML = (new Date()).toLocaleTimeString() + ": " + sender.element.id + " error: " + evt.errorMessage + " error code: " + evt.errorCode + "<br>" + adEvents.innerHTML;
                console.log("errorhandler hit. \n");
            });

            function getStatus() {
                if(myAdControl.isSuspended){
                    //document.getElementById("state").innerText = "The Ad has been suspended";
                    //myAdControl.suspend();
                    WinJS.log && WinJS.log("The ad has been suspended","sample","error");
                }
                else{
                    //document.getElementById("state").innerText = "The Ad is running normally";
                    WinJS.log && WinJS.log("The ad is running normally","sample","status");
                }
            }


            //fb stuff
            // UTILITIES

            // AUTHENTICATION
            function loginClicked() {

                if (access_token) {
                    postClicked();
                }
                else {
                    askForPermissions('user_about_me read_stream status_update share_item publish_stream publish_actions publish_checkins user_videos video_upload photo_upload share_item read_friendlists manage_friendlists', function (error, result) {
                        if (error) {
                            console.log(error);
                            return;
                        } else {
                            if (result.access_token) {

                                access_token = result.access_token;
                                postClicked();

                            }
                        }
                    });
                }
            }

            function postClicked() {

                FB.setAccessToken(access_token);

                var body = 'I like this app';
                FB.api('me/feed', 'post', {
                    message: body, link: "", caption: "Social Promotional Video", name: "TicTac", source: "http://ie.microsoft.com/testdrive/Videos/BehindIE9AllAroundFast/Video.mp4", type: 'video'
                }, function (res) {
                    if (!res || res.error) {
                        console.log(!res ? 'error occurred' : res.error);
                        WinJS.log && WinJS.log("share failed.", "sample", "error");
                        share = false;
                        return;
                    }
                    else {
                        console.log('Post Id: ' + res.id);
                        WinJS.log && WinJS.log("Thank You for sharing. The ad has been removed", "sample", "status");
                        share = true;
                    }

                    if (share === true) {
                            myAd.innerText = "";
                            myAdControl.suspend();
                            share = false;
                    }
                    else {
                        WinJS.log && WinJS.log("share failed.", "sample", "error");
                    }
                });



            }

            function askForPermissions(scope, callback) {

                var redirectUri = 'https://www.facebook.com/connect/login_success.html',
                    loginUrl = FB.getLoginUrl({ scope: scope });

                try {

                    Windows.Security.Authentication.Web.WebAuthenticationBroker.authenticateAsync(
                        Windows.Security.Authentication.Web.WebAuthenticationBroker.default,
                        new Windows.Foundation.Uri(loginUrl),
                        new Windows.Foundation.Uri(redirectUri))
                        .then(function success(result) {
                            if (result.responseStatus == 2) {
                                console.log('error: ' + result.responseerrordetail);
                                callback(new Error(result.responseerrordetail));
                                return;
                            }

                            var parser = document.createElement('a');
                            parser.href = result.responseData;

                            var qs = extractQuerystring(parser.hash.substr(1).split('&'));

                            if (qs.error) {
                                // most likely user clicked don't allow
                                console.log('error: ' + qs.error + ' : ' + qs.error_description);
                                return;
                            }

                            // set it as the default access token.
                            FB.setAccessToken(qs.access_token);

                            callback(null, qs);

                        }, function error(err) {
                            console.log('Error Number: ' + err.number);
                            console.log('Error Message: ' + err.message);
                            callback(new Error(err.message));
                        });

                } catch (e) {
                    // error launching web auth
                    console.log(e);
                }
            }

            function extractQuerystring(a) {
                if (a == "") return {};
                var b = {};
                for (var i = 0; i < a.length; ++i) {
                    var p = a[i].split('=');
                    if (p.length != 2) continue;
                    b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
                }
                return b;
            }

            function shareProduct2() {
                loginClicked();               
            }
        },
        unload: function () {
            /*The code in unload function goes into the block of your app.unload() function */
        }
    });
 

})();